package controler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.List;
import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.jasper.tagplugins.jstl.core.Out;

import report.Sokhachhangmoitrongthang;

import model.HoadonModel;
import model.SanphamModel;
import model.ShoppingCartModel;
import model.UpfileModel;

import dao.GetCnn;
import entity.CTHD;

/**
 * Servlet implementation class saveorder
 */
@WebServlet("/saveorder")
public class saveorder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public saveorder() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws SQLException 
	 * @throws IOException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    @SuppressWarnings("unchecked")
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{
    	Connection cnn = GetCnn.getCnn();
		Statement stat = cnn.createStatement();
		int madcgh = 0; 
		HttpSession session = request.getSession();
		String tenlogin =(String)session.getAttribute("userName");
		if((Integer) session.getAttribute("madcgh")!=null){
			madcgh = (Integer) session.getAttribute("madcgh");
		}
		SanphamModel model = new SanphamModel();
		int mahd = model.getTotalRows("select * from HOADON");
		String makh = model.get1column("select MAKH from KHACHHANG where TENDANGNHAP = '" +tenlogin+ "'");
		String sSQL = "insert into HOADON values ('"+mahd+"','"+makh+"','"+madcgh+"',getdate(),'','pending','')"; 
		stat.executeUpdate(sSQL);
		ShoppingCartModel cart = new ShoppingCartModel();
		//cart.clearItems();
		//Enumeration enum1= (Enumeration)session.getAttribute("itemsEnum");
		
		//String []tmpItem2 = (String[]) session.getAttribute("tmpItem");
		java.util.List<CTHD> listfuck = new java.util.ArrayList<CTHD>();
		listfuck = (List<CTHD>) session.getAttribute("listfuck");
		Enumeration enum1 = cart.getEnumeration();
		String[] tmpItem;
		String ma_sp= "";
		while(enum1.hasMoreElements()){
			tmpItem = (String[])enum1.nextElement();
			ma_sp = tmpItem[0];
			String soluong = tmpItem[3];
			String dongia = tmpItem[2];
			sSQL = "insert into CTHD values('"+mahd+"','"+ma_sp+"','"+soluong+"','"+dongia+"')";
			stat.executeUpdate(sSQL);
//			CallableStatement cstmt;
//			cstmt = cnn.prepareCall("{call proc_muahangcung1luc(?,?,?,?)}",
//	                ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                ResultSet.CONCUR_READ_ONLY);
//			cstmt.setInt(1, mahd);
//			cstmt.setString(2, ma_sp);
//			cstmt.setString(3, soluong);
//			cstmt.setString(4, dongia);
//			cstmt.execute();
//			cstmt.close();
			
//			CallableStatement cstmt1=cnn.prepareCall("{call proc_muahang(?)}",
//	                ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                ResultSet.CONCUR_READ_ONLY);
//			cstmt1.setString(1, ma_sp);
//			cstmt1.execute();
		}
		
		
		for(int i = 0 ;i<listfuck.size();i++)
		{
			sSQL = "insert into CTHD values('"+mahd+"','"+listfuck.get(i).getMasp()+"','"+listfuck.get(i).getSoluong()+"','"+listfuck.get(0).getDongia()+"')";
			stat.executeUpdate(sSQL);
			
//			CallableStatement cstmt;
//			cstmt = cnn.prepareCall("{call proc_muahangcung1luc(?,?,?,?)}",
//	                ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                ResultSet.CONCUR_READ_ONLY);
//			cstmt.setInt(1, mahd);
//			cstmt.setString(2, listfuck.get(i).getMasp());
//			cstmt.setInt(3, listfuck.get(i).getSoluong());
//			cstmt.setInt(4, listfuck.get(i).getDongia());
//			cstmt.execute();
//			session.setAttribute("mahd", mahd);
//			response.sendRedirect("ShoppingCart.jsp?cartAction=clear");
//			
//			
//			PrintWriter out = response.getWriter();
//			
			
//			CallableStatement cstmt1;
//			cstmt1=cnn.prepareCall("{call proc_muahang(?,?,?,?,?)}",
//	                ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                ResultSet.CONCUR_READ_ONLY);
//			cstmt1.setInt(1, mahd);
//			cstmt1.setString(2, listfuck.get(i).getMasp());
//			cstmt1.setInt(3, listfuck.get(i).getSoluong());
//			cstmt1.setInt(4, listfuck.get(i).getDongia());
//		 	cstmt1.registerOutParameter(5, java.sql.Types.INTEGER);
//		 	cstmt1.execute();
//		 	int s=cstmt1.getInt(5);
//		 	if(s==0){
//		 		session.setAttribute("mahd", mahd);
//				response.sendRedirect("ShoppingCart.jsp?cartAction=clear");
//		 	}
//		 	else
//		 		out.println("Khong the mua san pham nay");

		}
		
		session.setAttribute("mahd", mahd);
		
		HoadonModel hdmodel = new HoadonModel();
		String doanhso = hdmodel.getdoanhso("select MAHD, SUM(TRIGIA)AS DOANHSO from (select hoadon.MAHD,TENSP,CTHD.SOLUONG,DONGIA,hoten,(CTHD.SOLUONG*DONGIA)AS TRIGIA from CTHD ,SANPHAM,khachhang,hoadon where CTHD.MASP = SANPHAM.MASP and hoadon.makh = khachhang.makh and cthd.mahd= hoadon.mahd and hoadon.mahd='"+mahd+"')AS VT_TABLE GROUP BY MAHD");
		
		UpfileModel umodel = new UpfileModel();
		String targetFolder = "D:/";
		String path=getServletContext().getRealPath("reports");
		path = umodel.get_report_path(path)+"hoadon.jrxml";
		Sokhachhangmoitrongthang a = new Sokhachhangmoitrongthang();
		a.hoadon(mahd, doanhso, targetFolder, path);
		
		response.sendRedirect("ShoppingCart.jsp?cartAction=clear");
		//response.sendRedirect("saveOrder.jsp");
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.println("Khong the mua san pham nay");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.println("Khong the mua san pham nay");
		}
	}

}
